﻿using System;
using System.Text.RegularExpressions;

namespace MockNetCore.Handlers
{
    public class NumberHandler : TypeHandler
    {
        public object handle(Options options)
        {
            if (options.rule.isDecimal)
            {
                String[] parts = options.template.ToString().Split(new char[] { '.' });
                // 'float1|.1-10': 10,
                // 'float2|1-100.1-10': 1,
                // 'float3|999.1-10': 1,
                // 'float4|.3-10': 123.123,
                parts[0] = options.rule.isRange ? options.rule.count.ToString() : parts[0];
                if (parts.Length == 1)
                {
                    parts = new String[] { parts[0], "" };
                }

                // 如果预设值的小数位长度足够
                if (parts[1].Length >= options.rule.dcount)
                {
                    parts[1] = parts[1].Substring(0, options.rule.dcount.Value);
                }
                else
                {
                    while (parts[1].Length < options.rule.dcount)
                    {
                        parts[1] += new Random().Next(1, 10);
                    }
                }
                return new decimal(double.Parse(String.Join(".", parts)));
            }

            // 'grade1|1-100': 1,
            if (options.rule.isRange)
            {
                return options.rule.count;
            }

            // "number|+1": 202
            int? lastValue = options.context.incInitValue != null ? options.context.incInitValue : int.Parse(options.template + "");
            options.context.incInitValue = (lastValue.Value + 1);
            return options.context.incInitValue;
        }

        public Type[] support()
        {
            return new Type[] { typeof(Int32), typeof(decimal), typeof(Int64), typeof(double), typeof(float) };
        }
    }
}